package com.truthbean.jeetb.utils.web;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DBOperator {
    private Connection conn = null;
    private Statement stmt = null;
    private String driver;
    private String url;
    private String uid;
    private String pwd;

    public Connection getConn() {
        return conn;
    }

    public Statement getStmt() {
        return stmt;
    }

    public String getDriver() {
        return driver;
    }

    public String getUrl() {
        return url;
    }

    public String getUid() {
        return uid;
    }

    public String getPwd() {
        return pwd;
    }

    public DBOperator(String driver, String url, String uid, String pwd) throws Exception {
        this(driver, url, uid, pwd, false);
    }

    public DBOperator(String driver, String url, String uid, String pwd, boolean connect) throws Exception {
        Class.forName(driver);
        if (connect)
            this.conn = DriverManager.getConnection(url, uid, pwd);
        this.url = url;
        this.driver = driver;
        this.uid = uid;
        this.pwd = pwd;
    }

    public void connect() throws Exception {
        this.conn = DriverManager.getConnection(url, uid, pwd);
    }

    public Object execute(String sql) throws Exception {
        if (isValid()) {
            stmt = conn.createStatement();
            if (stmt.execute(sql)) {
                return stmt.getResultSet();
            } else {
                return stmt.getUpdateCount();
            }
        }
        throw new Exception("Connection is inValid.");
    }

    public void closeStmt() throws Exception {
        if (this.stmt != null)
            stmt.close();
    }

    public boolean isValid() throws Exception {
        return conn != null && !conn.isClosed();
    }

    public void close() throws Exception {
        if (isValid()) {
            closeStmt();
            conn.close();
        }
    }

    public boolean equals(Object o) {
        if (o instanceof DBOperator) {
            DBOperator dbo = (DBOperator) o;
            return this.driver.equals(dbo.driver) && this.url.equals(dbo.url) && this.uid.equals(dbo.uid) && this.pwd.equals(dbo.pwd);
        }
        return false;
    }
}